import { baseURL, flieUrl } from "./config"
const app = getApp()

// 封装成类 -> 实例
class ZRRequest {
  constructor(baseURL) {
    this.baseURL = baseURL
  }
  request(options) {
    const { url } = options
    return new Promise((resolve, reject) => {
      wx.request({
        ...options,
        header: {
          Authorization: 'Bearer ' + wx.getStorageSync('token') || ""
        },
        url: this.baseURL + url,
        success: (res) => {
          if(res.data.code === 401 && res.data.msg == "登录状态已过期"){
            // wx.removeStorageSync('token')
            // wx.removeStorageSync('userInfo')
            // wx.removeStorageSync('appid')
            // wx.removeStorageSync('secret')
            // if(wx.getStorageSync('spaceId')){
            //   wx.removeStorageSync('spaceId')
            // }
            wx.clearStorage()
            app.globalData.userInfo = null
          }
          resolve(res.data)
        },
        fail: (err) => {
          console.log("err:", err);
        }
      })
    })
  }
  get(options) {
    return this.request({ ...options, method: "get" })
  }

  post(options) {
    return this.request({ ...options, method: "post" })
  }

  put(options) {
    return this.request({ ...options, method: "put" })
  }

  delete(options) {
    return this.request({ ...options, method: "delete" })
  }
}

export const zrRequest = new ZRRequest(baseURL)
export const zrRequestFile = new ZRRequest(flieUrl)

